package com.dream.base.web.provider.impl;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dream.app.cache.AppUserResourceCache;
import com.dream.model.app.AppAbstractUser;
import com.dream.model.app.AppResource;
import com.dream.utils.web.provider.AuthorityProvider;
import com.dream.vo.base.Constants;
import com.google.common.collect.Sets;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013/08/30
 */
@Service("authorityProvider")
public class AppAuthorityProviderImpl implements AuthorityProvider {

	@Autowired
	private AppUserResourceCache	appUserResourceCache;

	@Override
	public void refreshAll() {

	}

	@Override
	public boolean hasAuthority(HttpServletRequest request, String[] pageAutority) {

		boolean hasAuthority = false;
		AppAbstractUser user = getLoginUser(request);

		if (user != null) {

			if (ArrayUtils.isNotEmpty(pageAutority)) {// page authority tag

				hasAuthority = validateByName(user, Sets.newHashSet(pageAutority));

			} else {// controller authority

				hasAuthority = validateByUri(user, request);

			}
		}
		return hasAuthority;
	}

	private AppAbstractUser getLoginUser(HttpServletRequest httpRequest) {

		HttpSession session = httpRequest.getSession(false);
		if (session == null) {
			return null;
		}
		return (AppAbstractUser) session.getAttribute(Constants.USER_ID);

	}

	private boolean validateByName(AppAbstractUser user, Set<String> pageAutority) {

		boolean isOK = false;
		Set<AppResource> myResources = appUserResourceCache.getMyResources(user);
		if (CollectionUtils.isNotEmpty(myResources)) {
			for (AppResource res : myResources) {

				if (pageAutority.contains(res.getAliasName())) {
					isOK = true;
					break;
				}
			}
		}

		return isOK;
	}

	private boolean validateByUri(AppAbstractUser user, HttpServletRequest request) {

		boolean isOK = false;
		Set<AppResource> myResources = appUserResourceCache.getMyResources(user);
		String reqUri = request.getRequestURL().toString();

		if (CollectionUtils.isNotEmpty(myResources) && StringUtils.isNotBlank(reqUri)) {
			for (AppResource res : myResources) {
				if (StringUtils.isNotBlank(res.getUri())) {
					String[] uris = res.getUri().split(",");
					if (ArrayUtils.isNotEmpty(uris)) {
						for (String uri : uris) {
							if (reqUri.contains(uri)) {
								isOK = true;
								break;
							}
						}
					}
				}
			}
		}
		return isOK;
	}
}
